const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const mobileScreen = mobile => {
  // var tel = "18827768782";
  var reg = /^(\d{3})\d{4}(\d{4})$/;
  var tel = mobile.replace(reg, "$1****$2");
  return tel;
}

const cloneDeep = (source) => {
  const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象
  for(let keys in source){ // 遍历目标
    if(source.hasOwnProperty(keys)){
      if(source[keys] && typeof source[keys] === 'object'){ // 如果值是对象，就递归一下
        targetObj[keys] = source[keys].constructor === Array ? [] : {};
        targetObj[keys] = cloneDeep(source[keys]);
      }else{ // 如果不是，就直接赋值
        targetObj[keys] = source[keys];
      }
    }
  }
  return targetObj;
} 

let getQueryString = function(url, name) {
	var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
	var r = url.substr(1).match(reg)
	if (r != null) {
		return r[2]
	}
	return null;
}

/**
 * @param {callback} 需要防止多次点击的函数
 * @param {wait} 防止多次点击的等待时间
 */
let lock = true
let syncLock = function(callback, wait = 1000) {
	if (lock) {
		lock = false
		setTimeout(function() {
			lock = true
		}, wait)
		callback()
	}
}

let throttle = function throttle(fn, delay) {
	var previous = 0;
	// 使用闭包返回一个函数并且用到闭包函数外面的变量previous
	return function() {
		var _this = this;
		var args = arguments;
		var now = new Date();
		if (now - previous > delay) {
			fn.apply(_this, args);
			previous = now;
		}
	}
}


const identityCardFormat = function(val) {
    return val.replace(/(\d{6})\d*(.{4})/, '$1****$2')
}

module.exports = {
  formatTime: formatTime,
  mobileScreen,
  cloneDeep,
  getQueryString,
  syncLock,
  throttle,
  identityCardFormat,
}
